<template>
  <div id="manageQuestionView">
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
      column-resizable :bordered="{cell:true}"
    >
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD") }}
      </template>

      <template #extra="{ record }">
        <a-space wrap>
          <a-tag
            v-for="(tag, index) of JSON.parse(record.tags)"
            :key="index"
            color="green"
          >{{ tag }}
          </a-tag>
        </a-space>
      </template>

      <template #judgeConfig="{ record }">
        <a-space wrap>
          <a-tag
            color="purple"
          >时间限制:{{ JSON.parse(record.judgeConfig).timeLimit }}
          </a-tag>
          <a-tag
            color="cyan"
          >内存限制:{{ JSON.parse(record.judgeConfig).memoryLimit }}
          </a-tag>
          <a-tag
            color="gold"
          >堆栈限制:{{ JSON.parse(record.judgeConfig).stackLimit }}
          </a-tag>
        </a-space>
      </template>

      <template #judgeCase="{ record }">
        <a-space wrap>
          <template v-for="(tag, index) in JSON.parse(record.judgeCase)" :key="index">
            <a-tag v-if="tag.input" color="blue">
              示例输入:{{ tag.input }}
            </a-tag>
            <a-tag v-if="tag.output" color="green">
              示例输出:{{ tag.output }}
            </a-tag>
          </template>
        </a-space>
      </template>


      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="doUpdate(record)"> 修改</a-button>
          <a-button status="danger" @click="doDelete(record)">删除</a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import { BaseResponse_Page_Question_, Question, QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment/moment";

const tableRef = ref();

const dataList = ref([]);
const total = ref(0);
const searchParams = ref({
  pageSize: 10,
  current: 1
});


const loadData = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    // 解析和过滤 judgeCase
    const filteredDataList = res.data.records.map(record => {
      try {
        // 解析 judgeCase 字符串为数组
        const parsedJudgeCase = JSON.parse(record.judgeCase);
        // 过滤掉 input 和 output 均为空的项
        const filteredJudgeCase = parsedJudgeCase.filter(item => item.input.trim() !== "" || item.output.trim() !== "");
        // 将过滤后的数组重新赋值给 record.judgeCase
        record.judgeCase = JSON.stringify(filteredJudgeCase);
      } catch (error) {
        console.error("解析 judgeCase 错误:", error);
        // 如果解析失败，保留原始字符串
      }
      return record;
    });

    // 更新 dataList 和 total
    dataList.value = filteredDataList;
    total.value = filteredDataList.length; // 如果需要根据过滤后的数据更新总数
  } else {
    message.error("加载失败，" + res.message);
  }
};
/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

// {id: "1", title: "A+ D", content: "新的题目内容", tags: "["二叉树"]", answer: "新的答案", submitNum: 0,…}

const columns = [
  {
    title: "id",
    dataIndex: "id"
  },
  {
    title: "标题",
    dataIndex: "title"
  },
  {
    title: "内容",
    dataIndex: "content"
  },
  {
    title: "标签",
    slotName: "extra"
  },
  {
    title: "答案",
    dataIndex: "answer"
  },
  {
    title: "提交数",
    dataIndex: "submitNum"
  },
  {
    title: "通过数",
    dataIndex: "acceptedNum"
  },
  {
    title: "判题配置",
    slotName: "judgeConfig"
  },
  {
    title: "判题用例",
    slotName: "judgeCase"
  },
  {
    title: "用户id",
    dataIndex: "userId"
  },
  {
    title: "创建时间",
    slotName: "createTime"
  },
  {
    title: "操作",
    slotName: "optional"
  }
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page
  };
};

const doDelete = async (question: Question) => {
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: question.id
  });
  if (res.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败");
  }
};

const router = useRouter();

const doUpdate = (question: Question) => {
  router.push({
    path: "/update/question",
    query: {
      id: question.id
    }
  });
};
</script>

<style scoped>
#manageQuestionView {
}
</style>